<?php

namespace app\api\command;

use app\extra\wx\WxSdk;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Log;

class ExtensionNotice extends Command
{

    protected function configure()
    {
        $this->setName('extension_notice')->setDescription('新人奖励卡即将到期，下发通知');
    }

    protected function execute(Input $input, Output $output)
    {
        ini_set('default_socket_timeout', -1);  //不超时
        $redis = new \Redis();
        $redis->pconnect(config('redis.host'), config('redis.port'), config('redis.timeout'));
        $redis->select(9);

        // 新人奖励卡即将到期
        $redis->psubscribe(['__keyevent@9__:expired'], function ($redis, $pattern, $channel, $message) use ($output) {
            try {
                $find = Db::name('extension')
                    ->alias('extension')
                    ->join('user user', 'user.id = extension.user_id')
                    ->where(['extension.id' => $message])
                    ->field('user.open_id')
                    ->find();

                // 下发通知
                $pay        = get_addon_config('epay');
                $app_id     = $pay['wechat']['app_id'];
                $app_secret = $pay['wechat']['app_secret'];
                $data       = [
                    'thing1' => ['value' => '新人奖励三日卡'],
                    'thing3' => ['value' => '您的三日卡在三天后到期'],
                    'thing4' => ['value' => '您的三日卡即将到期，点击查看详情'],
                ];
                $result     = (new WxSdk($app_id, $app_secret))->subscribeSend($find['open_id'], 'B77QTMz8gwX85HzRvPb8FXVSDDD21ETcXoSYB0YSJkc', 'pages/login/guide/index', $data);
                Log::info($result);
                Log::info('EXTENSION_NOTICE 订单号：' . $message);
            } catch (\Exception $e) {
                // 记录错误日志
                Log::error('新人奖励卡即将到期');
                Log::info('EXTENSION_NOTICE 订单号：' . $message);
                Log::error($e->getMessage());
            }
        });
    }
}

